package logger

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/xinglou123/pkg/os/conv"
	"github.com/xinglou123/pkg/utils"
	"net/http"
)

type ApiLogger struct{}

func (al ApiLogger) Router(router *gin.Engine) {
	r := router.Group("logger")
	r.GET("list", al.loggerList)
	r.GET("info/:id", al.loggerInfo)
	r.POST("edit", al.loggerEdit)
	r.POST("delete", al.loggerDelete)
	r.POST("create", al.loggerAdd)
}

//
func (al ApiLogger) loggerList(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)
	params := map[string]interface{}{}
	params["path"] = ctx.DefaultQuery("path", "")
	params["user_id"] = ctx.DefaultQuery("user_id", "")
	params["limit"] = ctx.DefaultQuery("limit", "10")
	params["page"] = ctx.DefaultQuery("page", "1")

	list, page, err := LoggerService.Query(params)
	if err != nil {
		result.Code = 100
		result.Msg = err.Error()
		return
	}
	data := map[string]interface{}{}
	data["lists"] = list
	data["page"] = page

	result.Data = data
	result.Code = 200
	result.Msg = "ok"
	return
}

//
func (al ApiLogger) loggerInfo(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)

	uid := ctx.Param("id")
	if uid == "" {
		result.Code = 100
		result.Msg = "参数异常"
		return
	}
	user, err := LoggerService.One(conv.Int64(uid))
	if err != nil {
		result.Code = 100
		result.Msg = err.Error()
		return
	}
	result.Data = user
	return
}

//
func (al ApiLogger) loggerAdd(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)

	var mlogger Logger
	if error := ctx.Bind(&mlogger); error != nil {
		result.Code = 100
		result.Msg = "参数异常"
		return
	}
	uuser, err := LoggerService.Add(mlogger)
	if err != nil {
		result.Code = 100
		result.Msg = err.Error()
		return
	}
	result.Msg = "添加科目成功"
	result.Data = uuser
	return
}

//
func (al ApiLogger) loggerDelete(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)

	uid := ctx.Param("ids")
	fmt.Println(ctx.PostFormArray("ids"))
	if len(uid) == 0 {
		result.Code = 100
		result.Msg = "参数异常"
		return
	}
	_, err := LoggerService.Delete(conv.Int64(uid))
	if err != nil {
		result.Code = 100
		result.Msg = "删除失败"
		return
	}
	result.Msg = "删除成功"
	return
}

//
func (al ApiLogger) loggerEdit(ctx *gin.Context) {
	result := utils.NewResponse()
	defer ctx.JSON(http.StatusOK, result)

	var mlogger Logger
	if ctx.Bind(&mlogger) != nil {
		result.Code = 100
		result.Msg = "参数异常"
		return
	}
	if mlogger.Id == 0 {
		result.Code = 100
		result.Msg = "请选择要修改"
		return
	}
	_, err := LoggerService.Update(mlogger)
	if err != nil {
		result.Code = 100
		result.Msg = "修改失败"
		return
	}
	result.Msg = "修改成功"
	return
}
